import {Content} from "antd/es/layout/layout";
import {Card, Layout, message, Modal, Pagination, Typography} from "antd";
import {type CSSProperties, forwardRef, useCallback, useEffect, useRef, useState} from "react";
import {deleteArticle as deleteArticleRequest, getArticles, type TArticle} from "../request/article.ts";
import {Link} from "react-router";
import {ElementDraggable} from "../component/ElementDraggable.tsx";
import '../assets/draggable.css'
import {Trash2} from "lucide-react";

export function ArticleManagement() {
    const [articles, setArticles] = useState<TArticle[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [current, setCurrent] = useState<number>(1);
    const [trashHadShow, setTrashHadShow] = useState<boolean>(false);

    const targetRef = useRef<HTMLSpanElement>(null);

    const resetArticles = useCallback(() => {
        getArticles(current).then((res) => {
            setArticles(res.data.body.data); // pagination data
            setTotal(res.data.body.total);
        })
    }, [current])


    useEffect(function () {
        resetArticles();
    });

    function deleteArticle(article: TArticle) {
        Modal.confirm({
            title: '你将要删除《' + article.title.slice(0, 20).concat("...") + '》',
            content: '这将无法逆转，你确认删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                deleteArticleRequest(article.id).then(data => {
                    const isDeleted = data.data.body
                    if (isDeleted) {
                        message.success("删除成功")
                        resetArticles();
                    } else {
                        message.warning("删除失败")
                    }
                })
            }
        })
    }

    return <Layout>
        <Typography.Title>所有文章</Typography.Title>
        <Content>
            {/* It may be to display a button to delete the article */}
            <Trash show={trashHadShow} ref={targetRef}/>
            {articles.map((article) =>
                <ElementDraggable
                    key={article.id}
                    getTrashRef={() => targetRef}
                    whenDraggingNotifier={(isDragging) => {
                        if (isDragging && !trashHadShow) {
                            setTrashHadShow(true);
                        }
                    }}
                    allStopped={(whateverDelete) => {
                        setTrashHadShow(false);
                        if (whateverDelete) {
                            deleteArticle(article);
                        }
                    }}
                >
                    <Card key={article.id} title={article.title} style={{
                        marginBottom: 20
                    }}
                          hoverable
                          variant="borderless"
                          extra={<Link to={`/homePage/articleViewer/${article.id}`}>编辑</Link>}>
                        {article.content.slice(50).concat("...")}
                    </Card>
                </ElementDraggable>
            )}
            <Pagination total={total} current={current} onChange={setCurrent}/>
        </Content>
    </Layout>
}

const Trash = forwardRef<any, { show: boolean }>((props, ref) => {
    const cssProperties: CSSProperties = {
        position: 'absolute',
        display: props.show ? 'flex' : 'none',
        // display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100vw',
        height: '100vh',
        background: 'black',
        opacity: 0.8,
        zIndex: 998,
        top: 0,
        left: 0,
    }

    return <div style={cssProperties}>
        <div style={{
            width: "50%",
            height: "50%",
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center'
        }}>
            <Trash2 className='trash' ref={ref} width="64" height="64"/>
        </div>
    </div>
})
